package com.education.welco.controller.teacherapp;

import com.education.common.pojo.AjaxResult;
import com.education.utils.JwtUtil;
import com.education.websocket.data.HomeBuffer;
import com.education.websocket.data.HomeData;
import com.education.websocket.server.WebSocketServerWELCO;
import com.education.welco.pojo.SCatalogWork;
import com.education.welco.pojo.StudentWork;
import com.education.welco.pojo.vo.SCatalogWorkApp;
import com.education.welco.pojo.vo.WholeWorkInfoApp;
import com.education.welco.service.ISCatalogWorkService;
import com.education.welco.service.ISTheoryClassroomService;
import com.education.welco.service.IStudentWorkService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Author: liftsail
 * @Date: 2023/1/16 13:48
 * @Description: 不积跬步无以至千里
 */
@RestController
@RequestMapping("/apptea/correctWorks")
public class AppTeaCorrectWorksController {

    @Autowired
    private ISCatalogWorkService catalogWorkService;
    @Autowired
    private ISTheoryClassroomService theoryClassroomService;
    @Autowired
    private IStudentWorkService studentWorkService;
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;
    @Autowired
    private JwtUtil jwtUtil;
    @Autowired
    private HomeBuffer homeBuffer;

    /**
     * 批改作业列表  作业列表(作业截止日期、作业内容、批改进度)
     *
     * @param teaId    老师用户id
     * @param pageNum  分页参数
     * @param pageSize 分页参数
     * @return 批改作业列表
     */
    @GetMapping("/workList")
    public AjaxResult workListByTeacher(@RequestParam(value = "teaId", required = false) Integer teaId,
                                        @RequestParam(value = "pageNum", required = false) Integer pageNum,
                                        @RequestParam(value = "pageSize", required = false) Integer pageSize) {
        if (pageNum != null && pageSize != null) {
            PageHelper.startPage(pageNum, pageSize);
        }
        List<SCatalogWorkApp> workList = catalogWorkService.selectWorkListForTea(teaId);
        return AjaxResult.success(new PageInfo<>(workList));
    }

    /**
     * 作业整体批改详情  根据作业id
     *
     * @param teaId     老师id
     * @param workId    作业id
     * @param catalogId 课程id
     * @param likeName  模糊匹配
     * @param pageNum   分页
     * @param pageSize  分页
     * @return 作业整体批改详情
     */
    @GetMapping("/wholeWorkInfo")
    public AjaxResult wholeWorkInfo(@RequestParam(value = "teaId", required = false) Integer teaId,
                                    @RequestParam(value = "workId", required = false) Integer workId,
                                    @RequestParam(value = "catalogId", required = false) Integer catalogId,
                                    @RequestParam(value = "likeName", required = false) String likeName,
                                    @RequestParam(value = "pageNum", required = false) Integer pageNum,
                                    @RequestParam(value = "pageSize", required = false) Integer pageSize) {
        Map<String, Object> map = new HashMap<>();
        if (pageNum != null && pageSize != null) {
            PageHelper.startPage(pageNum, pageSize);
        }
        //1.作业详情列表
        List<WholeWorkInfoApp> workList = catalogWorkService.wholeWorkInfo(workId, likeName);
        map.put("list", workList);
        //2.提交人数、未提交人数
        List<WholeWorkInfoApp> wholeWorkInfoApps = catalogWorkService.wholeWorkInfo(workId, null);
        int size = wholeWorkInfoApps.size();//已提交
        //未提交   课程找到班级
        Integer classStuNum = theoryClassroomService.selectClassStuNumByCatalogId(catalogId);
        int i = classStuNum - size;//未提交
        if (i < 0) {
            i = 0;
        }
        map.put("Submitted", size);
        map.put("Uncommitted", i);
        //3.最高分、最低分
        List<WholeWorkInfoApp> collect = wholeWorkInfoApps.parallelStream().sorted(Comparator.comparing(a -> a.getTeaScore())).collect(Collectors.toList());//正序
        if (collect.size() != 0) {
            WholeWorkInfoApp wholeWorkInfoApp = collect.get(0);//最低分
            map.put("low", wholeWorkInfoApp);
            WholeWorkInfoApp wholeWorkInfoApp1 = collect.get(collect.size() - 1);//最高分
            map.put("high", wholeWorkInfoApp1);
        } else {
            map.put("low", new WholeWorkInfoApp());
            map.put("high", new WholeWorkInfoApp());
        }
        return AjaxResult.success(map);
    }

    /**
     * 批改作业详情 根据学生作业id查找
     *
     * @param stuWorkId
     * @return
     */
    @GetMapping("/stuWorkInfo")
    public AjaxResult stuWorkInfo(@RequestParam(value = "stuWorkId") Integer stuWorkId) {
        Map<String, Object> result = new HashMap<>();
        //学生作业得分
        StudentWork studentWork = studentWorkService.selectStudentWorkByStuWorkId(stuWorkId);
        //作业详情
        SCatalogWork catalogWork = catalogWorkService.selectSCatalogWorkById(Integer.valueOf(studentWork.getTeaWorkId()));
        result.put("workname", catalogWork.getWorkName());
        result.put("worktext", catalogWork.getWorkText());
        result.put("stuname", studentWork.getUserName());
        result.put("answertext", studentWork.getWorkText());
        result.put("answerimg", studentWork.getWorkImage());
        result.put("workstate", studentWork.getWorkState());
        result.put("id", studentWork.getId());
        if (StringUtils.isBlank(studentWork.getTeaScore())) {
            result.put("teascore", "");
        } else {
            result.put("teascore", studentWork.getTeaScore());
        }
        if (StringUtils.isBlank(studentWork.getTeaRemark())) {
            result.put("tearemark", "");
        } else {
            result.put("tearemark", studentWork.getTeaRemark());
        }
        return AjaxResult.success(result);
    }

    /**
     * 作业批改接口  打分评语接口 驳回2、已完成3
     *
     * @param id        学生作业主键id
     * @param teaUserId 老师用户id
     * @param score     作业得分
     * @param remark    教师评语
     * @param workState 作业状态
     * @return
     */
    @GetMapping("/workMarkById")
    public AjaxResult workMarkById(@RequestParam(value = "id") Integer id,
                                   @RequestParam(value = "teaUserId") Integer teaUserId,
                                   @RequestParam(value = "score", required = false) BigDecimal score,
                                   @RequestParam(value = "remark", required = false) String remark,
                                   @RequestParam(value = "workState") Integer workState) {
        //判断该作业是否已经进行了批阅(状态判断)

        int i = catalogWorkService.workMarkById(id, score, remark, workState);
        //websocket数据更新-首页待批改作业数量减1
        //UserInfo userInfo = jwtUtil.getInfoFromToken();
        //Long teaUserId = userInfo.getId();
        Object res = redisTemplate.opsForValue().get("wait:data:" + teaUserId);
        if (Objects.nonNull(res)) {
            HomeData homeData = (HomeData) res;
            if (homeData.getWorkWait() > 0) {
                homeData.setWorkWait(homeData.getWorkWait() - 1);
            }
            redisTemplate.opsForValue().set("wait:data:" + teaUserId, homeData);
            WebSocketServerWELCO.sendInfo(homeData, String.valueOf(teaUserId));
        } else {
            //数据初始化
            Object data = homeBuffer.data(String.valueOf(teaUserId));
            HomeData homeData = (HomeData) data;
            if (homeData.getWorkWait() > 0) {
                homeData.setWorkWait(homeData.getWorkWait() - 1);
            }
            redisTemplate.opsForValue().set("wait:data:" + teaUserId, homeData);
            WebSocketServerWELCO.sendInfo(homeData, String.valueOf(teaUserId));
        }
        if (i == 0) {
            return AjaxResult.error("批改失败");
        }
        return AjaxResult.success("批改成功");
    }

}
